package com.gaoyi.basemodule.baseUtil;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class ThreadManager {
    private static volatile ThreadManager INSTANCE;
    private final ThreadPoolExecutor mExecutor;
    private final int mCorePoolSize;
    private final int mMaximumPoolSize;
    private final int mKeepAliveTime;

    private ThreadManager() {
        mCorePoolSize = Runtime.getRuntime().availableProcessors();
        mMaximumPoolSize = mCorePoolSize * 2 + 1;
        mKeepAliveTime = 2;
        mExecutor = new ThreadPoolExecutor(
                mCorePoolSize,
                mMaximumPoolSize,
                mKeepAliveTime,
                TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(50),
                new ThreadPoolExecutor.DiscardOldestPolicy()
        );
    }

    public static ThreadManager getInstance() {
        if (INSTANCE == null) {
            synchronized (ThreadManager.class) {
                if (INSTANCE == null) {
                    INSTANCE = new ThreadManager();
                }
            }
        }
        return INSTANCE;
    }

    public void execute(Runnable runnable) {
        if (runnable != null && !mExecutor.isShutdown()) {
            mExecutor.execute(runnable);
        }
    }
}
